<?php
/**
 * Created by PhpStorm.
 * User: fenfen
 * Date: 2016/12/21
 * Time: 13:53
 */

namespace backend\controllers;


use bc\controller\BackendController;
use bc\model\ExpressCompanyModel;
use bc\model\ExpressModel;
use bc\model\OrderbindMode;
use bc\model\wx\PayLog;
use yii\web\Session;
use bc\api\SzApi;
use bc\service\DictProvinceService;
use bc\model\OrderModel;
use bc\util\Util;
use yii;
use bc\util\backend\Page;

class ShopOrderController extends BackendController
{
    private static $product_id = 2;
    protected $arrStatus = [1 => '未支付', 2 => '已付款', 3 => '已发货', 5 => '已取消', 6 => '已完成'];


    public function actionIndex()
    {
        $model = new OrderModel();

        $sort_pay_time = $this->get('sort_pay_time', '');
        $sort_time = $this->get('sort_time', '');

        if(($sort_pay_time == '') && ($sort_time == '')){
            $sort = ' bc_order.create_time desc';
        }elseif($sort_pay_time == ''){
            if($sort_time == 'desc'){
                $sort = ' bc_order.create_time desc';
            }elseif($sort_time == 'asc'){
                $sort = 'bc_order.create_time asc';
            }else{
                $sort = 'bc_order.create_time desc';
            }
        }elseif($sort_time == ''){
            if($sort_pay_time == 'desc'){
                $sort = ' bc_order.pay_time desc';
            }elseif($sort_pay_time == 'asc'){
                $sort = 'bc_order.pay_time asc';
            }else{
                $sort = 'bc_order.pay_time desc';
            }
        }else{
            $sort = ' bc_order.create_time,bc_order.pay_time desc';
        }

        $start_time_str = $this->get('start_time', '');
        $end_time_str = $this->get('end_time', '');
        $start_time = $start_time_str ? strtotime($start_time_str) : '';
        $end_time = $end_time_str ? strtotime($end_time_str) : '';
        $params = ' bc_order_detail.product_id = '. self::$product_id .' ';
        if($start_time != '')
        {
            $params = $params." and bc_order.create_time >= {$start_time}";
        }

        if($end_time != '')
        {
            $end_time+=60*60*24;
            $params = $params." and bc_order.create_time <= {$end_time}";
        }

        //支付时间
        $pay_start_time_str = $this->get('pay_start_time', '');
        $pay_end_time_str = $this->get('pay_end_time', '');
        $pay_start_time = $pay_start_time_str ? strtotime($pay_start_time_str) : '';
        $pay_end_time = $pay_end_time_str ? strtotime($pay_end_time_str) : '';
        if($pay_start_time != '')
        {
            $params = $params." and bc_order.pay_time >= {$pay_start_time}";
        }

        if($pay_end_time != '')
        {
            $pay_end_time+=60*60*24;
            $params = $params." and bc_order.pay_time <= {$pay_end_time}";
        }

        //状态
        $order_status = $this->get('order_status', '');
        if($order_status != 0)
        {
            $params = $params." and bc_order.order_status = {$order_status}";
        }

        //状态
        $mobile = $this->get('mobile', '');
        if($mobile != 0)
        {
            $params = $params." and ecs_users.mobile = '{$mobile}'";
        }

        //昵称
        $nickname = $this->get('nickname', '');

        if(!empty($nickname))
        {
            $params = $params." and bc_wx_user.nickname like '%{$nickname}%'";
        }

        //收货人名称
        $addressee = $this->get('addressee', '');
        if(!empty($addressee))
        {
            $params = $params." and bc_order_address.addressee like '%{$addressee}%'";
        }
        $page = $this->get('page', 1);
        $model->sort=$sort;
        $model->columns='bc_order.order_id as oid,bc_order.create_time as ocreate_time,bc_order.pay_time as opay_time,bc_order.order_amount as oorder_amount,bc_product.product_id as pid,bc_order_detail.order_detail_id as did,bc_order_address.id as aid,bc_wx_user.id as wid,ecs_users.user_id as uid,bc_order_status.order_status_id as sid,bc_order_address.addressee as addressee_name,bc_order_address.telephone as add_telephone,bc_order_address.city as city_name,bc_order_address.province as province_name,bc_order_address.district as district_name,bc_order_address.address as address_name,bc_order.*,bc_product.*,bc_order_detail.*,bc_order_address.*,bc_wx_user.*,ecs_users.*,bc_order_status.*';

        $tag = $this->get('tag', 1);
        //等于2为到处功能
        if($tag == 2)
        {
            $list = $model->getList($params, 1, self::PAGE_SIZE+9999999);
            $model->excel($list);
            die();
        }

        $list = $model->getList($params, $page, self::PAGE_SIZE);
        $total = $model->getTotal($params);
        $pagination = new Page($total, self::PAGE_SIZE);

        $view['list'] = $list;
        $view['pagination'] = $pagination;
        $view['start_time'] = $start_time_str;
        $view['end_time'] = $end_time_str;
        $view['pay_start_time'] = $pay_start_time_str;
        $view['pay_end_time'] = $pay_end_time_str;
        $view['order_status'] = $order_status;
        $view['mobile'] = $mobile;
        $view['nickname'] = $nickname;
        $view['addressee'] = $addressee;
        $view['arrStatus'] = $this->arrStatus;
        return $this->render('index',$view);
    }

    public function actionOrderinfo()
    {
        $order_id = $this->get('id', '');
        if(empty($order_id)){
            $params['msg'] = '无order_id!';
            $params['url'] = '/shop-order/index';
            $this->forward($params);
        }
        $model = new OrderModel();
        $orderinfo = $model->getRow(['bc_order.order_id'=>$order_id]);
        $view['orderinfo']=$orderinfo[0];

        //省
        $provinceService = new DictProvinceService ();
        $provinceService->sort = 'id ASC';
        $provinceList = $provinceService->getList ();

        $view ['province'] = $provinceList;

        //获取快递公司
        $expresscompanyM = new ExpressCompanyModel();
        $expresscompanyM->sort = 'company_id ASC';
        $expresscompanyD=$expresscompanyM->getList(['is_invalid'=>0]);
        $view ['company'] = $expresscompanyD;

        //获取订单快递公司
        $expressM = new ExpressModel();
        $expressM->columns='bc_express_company.company_name,bc_express.tracking_no';
        $expressD=$expressM->getSendinfo(['bc_express.sign'=>0,'bc_express.order_id'=>$order_id]);
        $view ['express'] = empty($expressD) ? array():$expressD[0];

        //获取微信支付单号
        $payLog = new PayLog();
        $payLogD=$payLog->getRow(['order_no'=>$orderinfo[0]['order_no']]);
        $view ['paylog'] = $payLogD;

        //获取订单样本号信息
        $Orderbindm = new OrderbindMode();
        $Orderbindm->columns='
            bc_order_bind.bind_id as order_bind_id,bc_order_bind.bind_status as order_bind_status,bc_order_bind.bind_no as order_bind_no,bc_order_bind.user_id as order_user_id,bc_order_bind.bind_status as order_bind_status,
            bc_express.tracking_no as express_tracking_no,bc_express_company.company_name as company_company_name,bc_item_data.item_value as data_item_value,
            bc_item.report_key as item_report_key';

        $OrderbindD = $Orderbindm->getBindDetailedInfoFromOrderId($order_id);
        $view ['orderbindd'] = $OrderbindD;
        return $this->render('orderinfo',$view);
    }

    //ajax
    public function  actionAjaxdes()
    {
        $des = $this->post("des");
        $order_id = $this->post("order_id");

        empty($des) && Util::echoJosnData("请输入信息",1);
        empty($order_id) && Util::echoJosnData("请刷新重试",1);

        $model = new OrderModel();
        $model->autoId='order_id';
        $model->modify(['order_remark'=>$des],$order_id);
        Util::echoJosnData("备注成功",0,$des);
    }

    //取消订单
    public function actionAjaxrefund()
    {
        $order_id = $this->post("order_id");
        empty($order_id) && Util::echoJosnData("取消订单失败",1);
        $model = new OrderModel();
        $model->autoId='order_id';
        $model->modify(['cancellation_time'=>time(),'order_status'=>5],$order_id);
        Util::echoJosnData("取消订单成功",0);
    }

    //发货
    public function actionAjaxdelivery()
    {
        $session = new Session ();
        $shop_user = $session->get ( 'admin' );
        $account = $shop_user ['account'];

        //邮寄单信息
        $company = trim($this->post("company"));
        $order_id = trim($this->post("order_id"));
        $tracking_no = trim($this->post("tracking_no"));

        //回寄单信息
        $companyarr = json_decode(trim($this->post("companyarr")));
        $tracking_noarr = json_decode(trim($this->post("tracking_noarr")));
        $bind_noarr = json_decode(trim($this->post("bind_noarr")));

        if(empty($company)||empty($tracking_no)||!is_array($companyarr)|| !is_array($tracking_noarr)||!is_array($bind_noarr)||empty($order_id))
        {
            Util::echoJosnData("请确认数据是否输入正确",1);
        }

        $orderM = new OrderModel();
        $orderD = $orderM->getRowById($order_id);
        //判断订单是否支付陈公公
        ($orderD['order_status'] == 2) or Util::echoJosnData("订单状态不对",1);

        $orderbindM = new OrderbindMode();
        $orderbindM->autoId='bind_id';
        $orderbindD = $orderbindM->getList(['order_id'=>$order_id]);
        //判断是否已经绑定
        foreach($orderbindD as $key => $value)
        {
            ($value['bind_no'] == '') or Util::echoJosnData("订单号已绑定",1);
        }

        //验证样本编号，当时肥胖基因的时候
        foreach($tracking_noarr as $key => $value)
        {
            if($orderbindD[0]['product_id'] == 100) {
                //验证采样管编号
                $szapi = new SzApi();
                $szapiData = json_decode($szapi->searchInfo($value), true);
                if ($szapiData['retCode'] !== 0) {
                    Util::echoJosnData("验证失败，请检查录入编号！",1);
                }
            }
        }
        //修改订单状态
        $orderM->modify(['order_status'=>3, 'send_time'=>time(),'send_user'	=>$account,'update_time' => time()],$order_id);

        $expressM = new ExpressModel();
        //入快递信息
        $expressD = array(
            'tracking_no' => $tracking_no,
            'company_id' => (int)$company,
            'order_id' => (int)$order_id,
            'bind_id' => 0,
            'sign' =>  0,
            'is_invalid' =>  1,
            'create_time' =>  time(),
            'upate_time' =>  time()
        );
        $expressM->add($expressD);
        //入回寄单信息
        foreach($orderbindD as $key => $value)
        {
            $expressModel = new ExpressModel();
            //更新订单样板号
            $orderbindM->modify(['bind_no'=>$bind_noarr[$key],'bind_status' => 2,'update_time' => time()],$value['bind_id']);

            $expressData = array(
                'tracking_no'=>trim($tracking_noarr[$key]),
                'company_id'=>(int)$companyarr[$key],
                'order_id'=>0,
                'bind_id'=>(int)$value['bind_id'],
                'sign' =>1,
                'is_invalid' =>1,
                'create_time' =>time(),
                'upate_time' =>time()
            );

            $expressModel->add($expressData);
            unset($expressModel);
            unset($expressData);
        }

        Util::echoJosnData("成功",0);
    }
}